//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import type { NodeInfo } from '@/api/project_dataview';
import ProjectNodeWrap from '../ProjectNodeWrap';
import { Button, Descriptions, Space } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react';
import { useDataViewStores } from '@/pages/DataView/store';
import { get_case, type GetCaseResponse } from "@/api/project_testcase";
import { get_session } from '@/api/user';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import UserPhoto from '@/components/Portrait/UserPhoto';
import TestcaseDetailModal from '@/pages/Project/Testcase/TestcaseDetailModal';

const RefTestCaseNode = (props: NodeProps<NodeInfo>) => {
    const dataViewStore = useDataViewStores();

    const [dataResponse, setDataResponse] = useState<GetCaseResponse | null>(null);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [testCaseTab, setTestCaseTab] = useState<"detail" | "result" | "comment">("detail");

    const loadDataResponse = async () => {
        const sessionId = await get_session();
        const res = await get_case({
            session_id: sessionId,
            project_id: dataViewStore.projectStore.projectId,
            case_id: props.data.node_data.RefTargetId ?? "",
            sprit_id: "",
        });
        setDataResponse(res);
    };

    useEffect(() => {
        loadDataResponse();
    }, []);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.TestcaseNotice?.UpdateCaseNotice != undefined && notice.TestcaseNotice.UpdateCaseNotice.case_id == props.data.node_data.RefTargetId) {
                loadDataResponse();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <ProjectNodeWrap title="测试用例" nodeData={props} canChangeBgColor
            extraButtonList={[
                <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    loadDataResponse();
                }} />
            ]}>
            {dataResponse != null && (
                <>
                    {dataResponse.code != 0 && <span style={{ color: "red" }}>{dataResponse.err_msg}</span>}
                    {dataResponse.code == 0 && (
                        <div>
                            <a style={{ fontSize: "20px", fontWeight: 700 }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowDetailModal(true);
                            }}>{dataResponse.case_detail.case_info.title}</a>
                            <Descriptions column={1}>
                                <Descriptions.Item label="测试方法">
                                    <Space style={{ flexWrap: "wrap" }}>
                                        {dataResponse.case_detail.case_info.test_method.unit_test && "单元测试"}
                                        {dataResponse.case_detail.case_info.test_method.ci_test && "集成测试"}
                                        {dataResponse.case_detail.case_info.test_method.load_test && "压力测试"}
                                        {dataResponse.case_detail.case_info.test_method.manual_test && "手动测试"}
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="创建人">
                                    <Space>
                                        <UserPhoto logoUri={dataResponse.case_detail.case_info.create_logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                                        {dataResponse.case_detail.case_info.create_display_name}
                                    </Space>
                                </Descriptions.Item>
                            </Descriptions>
                        </div>
                    )}
                </>
            )}
            {showDetailModal == true && dataViewStore.projectStore.projectInfo != null && dataResponse != null && (
                <TestcaseDetailModal projectInfo={dataViewStore.projectStore.projectInfo} myUserId={dataViewStore.projectStore.myUserId}
                    testCaseId={props.data.node_data.RefTargetId ?? ""}
                    testCaseTab={testCaseTab} testCaseLinkSpritId={""}
                    onClose={() => {
                        setShowDetailModal(false)
                    }}
                    onChangeTab={newTab => setTestCaseTab(newTab)} />
            )}
        </ProjectNodeWrap>
    )
};

export default observer(RefTestCaseNode);
